//https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
//前序中序还原二叉树

class UsePreorderAndInorderCreateTree {
    static class TreeNode {
        public int val;
        public TreeNode left;//存储左孩子的引用
        public TreeNode right;//存储右孩子的引用

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public int preIndex;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
       return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }

    public TreeNode buildTreeChild(int[] preorder, int[] inorder,int inbegin,int inend) {
        //这种情况下 表明 当前root 没有子树了 
        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[preIndex]);
        int rootIndex = findVal(inorder,inbegin,inend,preorder[preIndex]);
        preIndex++;
        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);
        return root;
    }
    private int findVal(int[] inorder,int inbegin,int inend,int val) {
        for(int i = inbegin ;i <= inend;i++) {
            if(inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }
}